#include "widget.h"
#include "ui_widget.h"

#include <QTreeWidgetItem>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    // 设置根节点名字
    ui->treeWidget->setHeaderLabel("动物");

    // 设置顶部元素
    QTreeWidgetItem *top1 = new QTreeWidgetItem();
    top1->setText(0,"猫");
    ui->treeWidget->addTopLevelItem(top1);

    QTreeWidgetItem *top2 = new QTreeWidgetItem();
    top2->setText(0,"狗");
    ui->treeWidget->addTopLevelItem(top2);

    QTreeWidgetItem *top3 = new QTreeWidgetItem();
    top3->setText(0,"鱼");
    ui->treeWidget->addTopLevelItem(top3);


    // 设置一些子节点
    QTreeWidgetItem *item1 = new QTreeWidgetItem();
    item1->setText(0,"五皮毛");
    top1->addChild(item1);

    QTreeWidgetItem *item2 = new QTreeWidgetItem();
    item2->setText(0,"油皮毛");
    top1->addChild(item2);
}

Widget::~Widget()
{
    delete ui;
}


// 添加一个顶层元素
void Widget::on_pushButton_addTop_clicked()
{
    // 获取输入框内容
    const QString &str = ui->lineEdit->text();
    // 构建QTreeWidgetItem
    QTreeWidgetItem *item = new QTreeWidgetItem();
    item->setText(0,str);
    // 插入顶层
    ui->treeWidget->addTopLevelItem(item);
}

// 添加到选中位置
void Widget::on_pushButton_addItem_clicked()
{
    // 获取输入框内容
    const QString &str = ui->lineEdit->text();
    // 获取当前选中节点
    QTreeWidgetItem *pos = ui->treeWidget->currentItem();
    if(pos == nullptr)
    {
        return;
    }
    // 构建QTreeWidgetItem
    QTreeWidgetItem *item = new QTreeWidgetItem();
    item->setText(0,str);
    // 插入选中节点的子节点中
    pos->addChild(item);
}

// 删除选中元素
void Widget::on_pushButton_deleteItem_clicked()
{
    // 获取当前选中节点 要判断是为顶部元素还是子节点
    QTreeWidgetItem *pos = ui->treeWidget->currentItem();
    if(pos == nullptr)
    {
        return;
    }
    // 删除元素，需要获取到父亲元素，通过父亲元素进行删除
    QTreeWidgetItem *parent = pos->parent();
    if(parent == nullptr)
    {
        // 为顶部元素
        int p = ui->treeWidget->indexOfTopLevelItem(pos);
        ui->treeWidget->takeTopLevelItem(p);
    }
    else
    {
        // 为子节点
        parent->removeChild(pos);
    }
}

